Merge "Add abort method to mw.api"
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderFileModule.php
1 <?php
2 /**
3 * Resource loader module based on local JavaScript/CSS files.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
23 */
24
25 /**
26 * ResourceLoader module based on local JavaScript/CSS files.
27 */
28 class ResourceLoaderFileModule extends ResourceLoaderModule {
29 /* Protected Members */
30
31 /** @var string Local base path, see __construct() */
32 protected $localBasePath = '';
33
34 /** @var string Remote base path, see __construct() */
35 protected $remoteBasePath = '';
36
37 /** @var array Saves a list of the templates named by the modules. */
38 protected $templates = array();
39
40 /**
41 * @var array List of paths to JavaScript files to always include
42 * @par Usage:
43 * @code
44 * array( [file-path], [file-path], ... )
45 * @endcode
46 */
47 protected $scripts = array();
48
49 /**
50 * @var array List of JavaScript files to include when using a specific language
51 * @par Usage:
52 * @code
53 * array( [language-code] => array( [file-path], [file-path], ... ), ... )
54 * @endcode
55 */
56 protected $languageScripts = array();
57
58 /**
59 * @var array List of JavaScript files to include when using a specific skin
60 * @par Usage:
61 * @code
62 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
63 * @endcode
64 */
65 protected $skinScripts = array();
66
67 /**
68 * @var array List of paths to JavaScript files to include in debug mode
69 * @par Usage:
70 * @code
71 * array( [skin-name] => array( [file-path], [file-path], ... ), ... )
72 * @endcode
73 */
74 protected $debugScripts = array();
75
76 /**
77 * @var array List of paths to JavaScript files to include in the startup module
78 * @par Usage:
79 * @code
80 * array( [file-path], [file-path], ... )
81 * @endcode
82 */
83 protected $loaderScripts = array();
84
85 /**
86 * @var array List of paths to CSS files to always include
87 * @par Usage:
88 * @code
89 * array( [file-path], [file-path], ... )
90 * @endcode
91 */
92 protected $styles = array();
93
94 /**
95 * @var array List of paths to CSS files to include when using specific skins
96 * @par Usage:
97 * @code
98 * array( [file-path], [file-path], ... )
99 * @endcode
100 */
101 protected $skinStyles = array();
102
103 /**
104 * @var array List of modules this module depends on
105 * @par Usage:
106 * @code
107 * array( [file-path], [file-path], ... )
108 * @endcode
109 */
110 protected $dependencies = array();
111
112 /**
113 * @var string File name containing the body of the skip function
114 */
115 protected $skipFunction = null;
116
117 /**
118 * @var array List of message keys used by this module
119 * @par Usage:
120 * @code
121 * array( [message-key], [message-key], ... )
122 * @endcode
123 */
124 protected $messages = array();
125
126 /** @var string Name of group to load this module in */
127 protected $group;
128
129 /** @var string Position on the page to load this module at */
130 protected $position = 'bottom';
131
132 /** @var bool Link to raw files in debug mode */
133 protected $debugRaw = true;
134
135 /** @var bool Whether mw.loader.state() call should be omitted */
136 protected $raw = false;
137
138 protected $targets = array( 'desktop' );
139
140 /**
141 * @var bool Whether getStyleURLsForDebug should return raw file paths,
142 * or return load.php urls
143 */
144 protected $hasGeneratedStyles = false;
145
146 /**
147 * @var array Place where readStyleFile() tracks file dependencies
148 * @par Usage:
149 * @code
150 * array( [file-path], [file-path], ... )
151 * @endcode
152 */
153 protected $localFileRefs = array();
154
155 /**
156 * @var array Place where readStyleFile() tracks file dependencies for non-existent files.
157 * Used in tests to detect missing dependencies.
158 */
159 protected $missingLocalFileRefs = array();
160
161 /* Methods */
162
163 /**
164 * Constructs a new module from an options array.
165 *
166 * @param array $options List of options; if not given or empty, an empty module will be
167 * constructed
168 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
169 * to $IP
170 * @param string $remoteBasePath Base path to prepend to all remote paths in $options. Defaults
171 * to $wgResourceBasePath
172 *
173 * Below is a description for the $options array:
174 * @throws InvalidArgumentException
175 * @par Construction options:
176 * @code
177 * array(
178 * // Base path to prepend to all local paths in $options. Defaults to $IP
179 * 'localBasePath' => [base path],
180 * // Base path to prepend to all remote paths in $options. Defaults to $wgResourceBasePath
181 * 'remoteBasePath' => [base path],
182 * // Equivalent of remoteBasePath, but relative to $wgExtensionAssetsPath
183 * 'remoteExtPath' => [base path],
184 * // Equivalent of remoteBasePath, but relative to $wgStylePath
185 * 'remoteSkinPath' => [base path],
186 * // Scripts to always include
187 * 'scripts' => [file path string or array of file path strings],
188 * // Scripts to include in specific language contexts
189 * 'languageScripts' => array(
190 * [language code] => [file path string or array of file path strings],
191 * ),
192 * // Scripts to include in specific skin contexts
193 * 'skinScripts' => array(
194 * [skin name] => [file path string or array of file path strings],
195 * ),
196 * // Scripts to include in debug contexts
197 * 'debugScripts' => [file path string or array of file path strings],
198 * // Scripts to include in the startup module
199 * 'loaderScripts' => [file path string or array of file path strings],
200 * // Modules which must be loaded before this module
201 * 'dependencies' => [module name string or array of module name strings],
202 * 'templates' => array(
203 * [template alias with file.ext] => [file path to a template file],
204 * ),
205 * // Styles to always load
206 * 'styles' => [file path string or array of file path strings],
207 * // Styles to include in specific skin contexts
208 * 'skinStyles' => array(
209 * [skin name] => [file path string or array of file path strings],
210 * ),
211 * // Messages to always load
212 * 'messages' => [array of message key strings],
213 * // Group which this module should be loaded together with
214 * 'group' => [group name string],
215 * // Position on the page to load this module at
216 * 'position' => ['bottom' (default) or 'top']
217 * // Function that, if it returns true, makes the loader skip this module.
218 * // The file must contain valid JavaScript for execution in a private function.
219 * // The file must not contain the "function () {" and "}" wrapper though.
220 * 'skipFunction' => [file path]
221 * )
222 * @endcode
223 */
224 public function __construct(
225 $options = array(),
226 $localBasePath = null,
227 $remoteBasePath = null
228 ) {
229 // Flag to decide whether to automagically add the mediawiki.template module
230 $hasTemplates = false;
231 // localBasePath and remoteBasePath both have unbelievably long fallback chains
232 // and need to be handled separately.
233 list( $this->localBasePath, $this->remoteBasePath ) =
234 self::extractBasePaths( $options, $localBasePath, $remoteBasePath );
235
236 // Extract, validate and normalise remaining options
237 foreach ( $options as $member => $option ) {
238 switch ( $member ) {
239 // Lists of file paths
240 case 'scripts':
241 case 'debugScripts':
242 case 'loaderScripts':
243 case 'styles':
244 $this->{$member} = (array)$option;
245 break;
246 case 'templates':
247 $hasTemplates = true;
248 $this->{$member} = (array)$option;
249 break;
250 // Collated lists of file paths
251 case 'languageScripts':
252 case 'skinScripts':
253 case 'skinStyles':
254 if ( !is_array( $option ) ) {
255 throw new InvalidArgumentException(
256 "Invalid collated file path list error. " .
257 "'$option' given, array expected."
258 );
259 }
260 foreach ( $option as $key => $value ) {
261 if ( !is_string( $key ) ) {
262 throw new InvalidArgumentException(
263 "Invalid collated file path list key error. " .
264 "'$key' given, string expected."
265 );
266 }
267 $this->{$member}[$key] = (array)$value;
268 }
269 break;
270 // Lists of strings
271 case 'dependencies':
272 case 'messages':
273 case 'targets':
274 // Normalise
275 $option = array_values( array_unique( (array)$option ) );
276 sort( $option );
277
278 $this->{$member} = $option;
279 break;
280 // Single strings
281 case 'position':
282 $this->isPositionDefined = true;
283 case 'group':
284 case 'skipFunction':
285 $this->{$member} = (string)$option;
286 break;
287 // Single booleans
288 case 'debugRaw':
289 case 'raw':
290 $this->{$member} = (bool)$option;
291 break;
292 }
293 }
294 if ( $hasTemplates ) {
295 $this->dependencies[] = 'mediawiki.template';
296 // Ensure relevant template compiler module gets loaded
297 foreach ( $this->templates as $alias => $templatePath ) {
298 if ( is_int( $alias ) ) {
299 $alias = $templatePath;
300 }
301 $suffix = explode( '.', $alias );
302 $suffix = end( $suffix );
303 $compilerModule = 'mediawiki.template.' . $suffix;
304 if ( $suffix !== 'html' && !in_array( $compilerModule, $this->dependencies ) ) {
305 $this->dependencies[] = $compilerModule;
306 }
307 }
308 }
309 }
310
311 /**
312 * Extract a pair of local and remote base paths from module definition information.
313 * Implementation note: the amount of global state used in this function is staggering.
314 *
315 * @param array $options Module definition
316 * @param string $localBasePath Path to use if not provided in module definition. Defaults
317 * to $IP
318 * @param string $remoteBasePath Path to use if not provided in module definition. Defaults
319 * to $wgResourceBasePath
320 * @return array Array( localBasePath, remoteBasePath )
321 */
322 public static function extractBasePaths(
323 $options = array(),
324 $localBasePath = null,
325 $remoteBasePath = null
326 ) {
327 global $IP, $wgResourceBasePath;
328
329 // The different ways these checks are done, and their ordering, look very silly,
330 // but were preserved for backwards-compatibility just in case. Tread lightly.
331
332 if ( $localBasePath === null ) {
333 $localBasePath = $IP;
334 }
335 if ( $remoteBasePath === null ) {
336 $remoteBasePath = $wgResourceBasePath;
337 }
338
339 if ( isset( $options['remoteExtPath'] ) ) {
340 global $wgExtensionAssetsPath;
341 $remoteBasePath = $wgExtensionAssetsPath . '/' . $options['remoteExtPath'];
342 }
343
344 if ( isset( $options['remoteSkinPath'] ) ) {
345 global $wgStylePath;
346 $remoteBasePath = $wgStylePath . '/' . $options['remoteSkinPath'];
347 }
348
349 if ( array_key_exists( 'localBasePath', $options ) ) {
350 $localBasePath = (string)$options['localBasePath'];
351 }
352
353 if ( array_key_exists( 'remoteBasePath', $options ) ) {
354 $remoteBasePath = (string)$options['remoteBasePath'];
355 }
356
357 // Make sure the remote base path is a complete valid URL,
358 // but possibly protocol-relative to avoid cache pollution
359 $remoteBasePath = wfExpandUrl( $remoteBasePath, PROTO_RELATIVE );
360
361 return array( $localBasePath, $remoteBasePath );
362 }
363
364 /**
365 * Gets all scripts for a given context concatenated together.
366 *
367 * @param ResourceLoaderContext $context Context in which to generate script
368 * @return string JavaScript code for $context
369 */
370 public function getScript( ResourceLoaderContext $context ) {
371 $files = $this->getScriptFiles( $context );
372 return $this->readScriptFiles( $files );
373 }
374
375 /**
376 * @param ResourceLoaderContext $context
377 * @return array
378 */
379 public function getScriptURLsForDebug( ResourceLoaderContext $context ) {
380 $urls = array();
381 foreach ( $this->getScriptFiles( $context ) as $file ) {
382 $urls[] = $this->getRemotePath( $file );
383 }
384 return $urls;
385 }
386
387 /**
388 * @return bool
389 */
390 public function supportsURLLoading() {
391 return $this->debugRaw;
392 }
393
394 /**
395 * Get loader script.
396 *
397 * @return string|bool JavaScript code to be added to startup module
398 */
399 public function getLoaderScript() {
400 if ( count( $this->loaderScripts ) === 0 ) {
401 return false;
402 }
403 return $this->readScriptFiles( $this->loaderScripts );
404 }
405
406 /**
407 * Get all styles for a given context.
408 *
409 * @param ResourceLoaderContext $context
410 * @return array CSS code for $context as an associative array mapping media type to CSS text.
411 */
412 public function getStyles( ResourceLoaderContext $context ) {
413 $styles = $this->readStyleFiles(
414 $this->getStyleFiles( $context ),
415 $this->getFlip( $context ),
416 $context
417 );
418 // Collect referenced files
419 $this->saveFileDependencies( $context, $this->localFileRefs );
420
421 return $styles;
422 }
423
424 /**
425 * @param ResourceLoaderContext $context
426 * @return array
427 */
428 public function getStyleURLsForDebug( ResourceLoaderContext $context ) {
429 if ( $this->hasGeneratedStyles ) {
430 // Do the default behaviour of returning a url back to load.php
431 // but with only=styles.
432 return parent::getStyleURLsForDebug( $context );
433 }
434 // Our module consists entirely of real css files,
435 // in debug mode we can load those directly.
436 $urls = array();
437 foreach ( $this->getStyleFiles( $context ) as $mediaType => $list ) {
438 $urls[$mediaType] = array();
439 foreach ( $list as $file ) {
440 $urls[$mediaType][] = $this->getRemotePath( $file );
441 }
442 }
443 return $urls;
444 }
445
446 /**
447 * Gets list of message keys used by this module.
448 *
449 * @return array List of message keys
450 */
451 public function getMessages() {
452 return $this->messages;
453 }
454
455 /**
456 * Gets the name of the group this module should be loaded in.
457 *
458 * @return string Group name
459 */
460 public function getGroup() {
461 return $this->group;
462 }
463
464 /**
465 * @return string
466 */
467 public function getPosition() {
468 return $this->position;
469 }
470
471 /**
472 * Gets list of names of modules this module depends on.
473 * @param ResourceLoaderContext context
474 * @return array List of module names
475 */
476 public function getDependencies( ResourceLoaderContext $context = null ) {
477 return $this->dependencies;
478 }
479
480 /**
481 * Get the skip function.
482 * @return null|string
483 * @throws MWException
484 */
485 public function getSkipFunction() {
486 if ( !$this->skipFunction ) {
487 return null;
488 }
489
490 $localPath = $this->getLocalPath( $this->skipFunction );
491 if ( !file_exists( $localPath ) ) {
492 throw new MWException( __METHOD__ . ": skip function file not found: \"$localPath\"" );
493 }
494 $contents = file_get_contents( $localPath );
495 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
496 $contents = $this->validateScriptFile( $localPath, $contents );
497 }
498 return $contents;
499 }
500
501 /**
502 * @return bool
503 */
504 public function isRaw() {
505 return $this->raw;
506 }
507
508 /**
509 * Disable module content versioning.
510 *
511 * This class uses getDefinitionSummary() instead, to avoid filesystem overhead
512 * involved with building the full module content inside a startup request.
513 *
514 * @return bool
515 */
516 public function enableModuleContentVersion() {
517 return false;
518 }
519
520 /**
521 * Helper method to gather file hashes for getDefinitionSummary.
522 *
523 * This function is context-sensitive, only computing hashes of files relevant to the
524 * given language, skin, etc.
525 *
526 * @see ResourceLoaderModule::getFileDependencies
527 * @param ResourceLoaderContext $context
528 * @return array
529 */
530 protected function getFileHashes( ResourceLoaderContext $context ) {
531 $files = array();
532
533 // Flatten style files into $files
534 $styles = self::collateFilePathListByOption( $this->styles, 'media', 'all' );
535 foreach ( $styles as $styleFiles ) {
536 $files = array_merge( $files, $styleFiles );
537 }
538
539 $skinFiles = self::collateFilePathListByOption(
540 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
541 'media',
542 'all'
543 );
544 foreach ( $skinFiles as $styleFiles ) {
545 $files = array_merge( $files, $styleFiles );
546 }
547
548 // Final merge, this should result in a master list of dependent files
549 $files = array_merge(
550 $files,
551 $this->scripts,
552 $this->templates,
553 $context->getDebug() ? $this->debugScripts : array(),
554 $this->getLanguageScripts( $context->getLanguage() ),
555 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' ),
556 $this->loaderScripts
557 );
558 if ( $this->skipFunction ) {
559 $files[] = $this->skipFunction;
560 }
561 $files = array_map( array( $this, 'getLocalPath' ), $files );
562 // File deps need to be treated separately because they're already prefixed
563 $files = array_merge( $files, $this->getFileDependencies( $context ) );
564 // Filter out any duplicates from getFileDependencies() and others.
565 // Most commonly introduced by compileLessFile(), which always includes the
566 // entry point Less file we already know about.
567 $files = array_values( array_unique( $files ) );
568
569 // Don't include keys or file paths here, only the hashes. Including that would needlessly
570 // cause global cache invalidation when files move or if e.g. the MediaWiki path changes.
571 // Any significant ordering is already detected by the definition summary.
572 return array_map( array( __CLASS__, 'safeFileHash' ), $files );
573 }
574
575 /**
576 * Get the definition summary for this module.
577 *
578 * @param ResourceLoaderContext $context
579 * @return array
580 */
581 public function getDefinitionSummary( ResourceLoaderContext $context ) {
582 $summary = parent::getDefinitionSummary( $context );
583
584 $options = array();
585 foreach ( array(
586 // The following properties are omitted because they don't affect the module reponse:
587 // - localBasePath (Per T104950; Changes when absolute directory name changes. If
588 // this affects 'scripts' and other file paths, getFileHashes accounts for that.)
589 // - remoteBasePath (Per T104950)
590 // - dependencies (provided via startup module)
591 // - targets
592 // - group (provided via startup module)
593 // - position (only used by OutputPage)
594 'scripts',
595 'debugScripts',
596 'loaderScripts',
597 'styles',
598 'languageScripts',
599 'skinScripts',
600 'skinStyles',
601 'messages',
602 'templates',
603 'skipFunction',
604 'debugRaw',
605 'raw',
606 ) as $member ) {
607 $options[$member] = $this->{$member};
608 };
609
610 $summary[] = array(
611 'options' => $options,
612 'fileHashes' => $this->getFileHashes( $context ),
613 'msgBlobMtime' => $this->getMsgBlobMtime( $context->getLanguage() ),
614 );
615 return $summary;
616 }
617
618 /**
619 * @param string|ResourceLoaderFilePath $path
620 * @return string
621 */
622 protected function getLocalPath( $path ) {
623 if ( $path instanceof ResourceLoaderFilePath ) {
624 return $path->getLocalPath();
625 }
626
627 return "{$this->localBasePath}/$path";
628 }
629
630 /**
631 * @param string|ResourceLoaderFilePath $path
632 * @return string
633 */
634 protected function getRemotePath( $path ) {
635 if ( $path instanceof ResourceLoaderFilePath ) {
636 return $path->getRemotePath();
637 }
638
639 return "{$this->remoteBasePath}/$path";
640 }
641
642 /**
643 * Infer the stylesheet language from a stylesheet file path.
644 *
645 * @since 1.22
646 * @param string $path
647 * @return string The stylesheet language name
648 */
649 public function getStyleSheetLang( $path ) {
650 return preg_match( '/\.less$/i', $path ) ? 'less' : 'css';
651 }
652
653 /**
654 * Collates file paths by option (where provided).
655 *
656 * @param array $list List of file paths in any combination of index/path
657 * or path/options pairs
658 * @param string $option Option name
659 * @param mixed $default Default value if the option isn't set
660 * @return array List of file paths, collated by $option
661 */
662 protected static function collateFilePathListByOption( array $list, $option, $default ) {
663 $collatedFiles = array();
664 foreach ( (array)$list as $key => $value ) {
665 if ( is_int( $key ) ) {
666 // File name as the value
667 if ( !isset( $collatedFiles[$default] ) ) {
668 $collatedFiles[$default] = array();
669 }
670 $collatedFiles[$default][] = $value;
671 } elseif ( is_array( $value ) ) {
672 // File name as the key, options array as the value
673 $optionValue = isset( $value[$option] ) ? $value[$option] : $default;
674 if ( !isset( $collatedFiles[$optionValue] ) ) {
675 $collatedFiles[$optionValue] = array();
676 }
677 $collatedFiles[$optionValue][] = $key;
678 }
679 }
680 return $collatedFiles;
681 }
682
683 /**
684 * Get a list of element that match a key, optionally using a fallback key.
685 *
686 * @param array $list List of lists to select from
687 * @param string $key Key to look for in $map
688 * @param string $fallback Key to look for in $list if $key doesn't exist
689 * @return array List of elements from $map which matched $key or $fallback,
690 * or an empty list in case of no match
691 */
692 protected static function tryForKey( array $list, $key, $fallback = null ) {
693 if ( isset( $list[$key] ) && is_array( $list[$key] ) ) {
694 return $list[$key];
695 } elseif ( is_string( $fallback )
696 && isset( $list[$fallback] )
697 && is_array( $list[$fallback] )
698 ) {
699 return $list[$fallback];
700 }
701 return array();
702 }
703
704 /**
705 * Get a list of file paths for all scripts in this module, in order of proper execution.
706 *
707 * @param ResourceLoaderContext $context
708 * @return array List of file paths
709 */
710 protected function getScriptFiles( ResourceLoaderContext $context ) {
711 $files = array_merge(
712 $this->scripts,
713 $this->getLanguageScripts( $context->getLanguage() ),
714 self::tryForKey( $this->skinScripts, $context->getSkin(), 'default' )
715 );
716 if ( $context->getDebug() ) {
717 $files = array_merge( $files, $this->debugScripts );
718 }
719
720 return array_unique( $files, SORT_REGULAR );
721 }
722
723 /**
724 * Get the set of language scripts for the given language,
725 * possibly using a fallback language.
726 *
727 * @param string $lang
728 * @return array
729 */
730 private function getLanguageScripts( $lang ) {
731 $scripts = self::tryForKey( $this->languageScripts, $lang );
732 if ( $scripts ) {
733 return $scripts;
734 }
735 $fallbacks = Language::getFallbacksFor( $lang );
736 foreach ( $fallbacks as $lang ) {
737 $scripts = self::tryForKey( $this->languageScripts, $lang );
738 if ( $scripts ) {
739 return $scripts;
740 }
741 }
742
743 return array();
744 }
745
746 /**
747 * Get a list of file paths for all styles in this module, in order of proper inclusion.
748 *
749 * @param ResourceLoaderContext $context
750 * @return array List of file paths
751 */
752 public function getStyleFiles( ResourceLoaderContext $context ) {
753 return array_merge_recursive(
754 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
755 self::collateFilePathListByOption(
756 self::tryForKey( $this->skinStyles, $context->getSkin(), 'default' ),
757 'media',
758 'all'
759 )
760 );
761 }
762
763 /**
764 * Gets a list of file paths for all skin styles in the module used by
765 * the skin.
766 *
767 * @param string $skinName The name of the skin
768 * @return array A list of file paths collated by media type
769 */
770 protected function getSkinStyleFiles( $skinName ) {
771 return self::collateFilePathListByOption(
772 self::tryForKey( $this->skinStyles, $skinName ),
773 'media',
774 'all'
775 );
776 }
777
778 /**
779 * Gets a list of file paths for all skin style files in the module,
780 * for all available skins.
781 *
782 * @return array A list of file paths collated by media type
783 */
784 protected function getAllSkinStyleFiles() {
785 $styleFiles = array();
786 $internalSkinNames = array_keys( Skin::getSkinNames() );
787 $internalSkinNames[] = 'default';
788
789 foreach ( $internalSkinNames as $internalSkinName ) {
790 $styleFiles = array_merge_recursive(
791 $styleFiles,
792 $this->getSkinStyleFiles( $internalSkinName )
793 );
794 }
795
796 return $styleFiles;
797 }
798
799 /**
800 * Returns all style files and all skin style files used by this module.
801 *
802 * @return array
803 */
804 public function getAllStyleFiles() {
805 $collatedStyleFiles = array_merge_recursive(
806 self::collateFilePathListByOption( $this->styles, 'media', 'all' ),
807 $this->getAllSkinStyleFiles()
808 );
809
810 $result = array();
811
812 foreach ( $collatedStyleFiles as $media => $styleFiles ) {
813 foreach ( $styleFiles as $styleFile ) {
814 $result[] = $this->getLocalPath( $styleFile );
815 }
816 }
817
818 return $result;
819 }
820
821 /**
822 * Gets the contents of a list of JavaScript files.
823 *
824 * @param array $scripts List of file paths to scripts to read, remap and concetenate
825 * @throws MWException
826 * @return string Concatenated and remapped JavaScript data from $scripts
827 */
828 protected function readScriptFiles( array $scripts ) {
829 if ( empty( $scripts ) ) {
830 return '';
831 }
832 $js = '';
833 foreach ( array_unique( $scripts, SORT_REGULAR ) as $fileName ) {
834 $localPath = $this->getLocalPath( $fileName );
835 if ( !file_exists( $localPath ) ) {
836 throw new MWException( __METHOD__ . ": script file not found: \"$localPath\"" );
837 }
838 $contents = file_get_contents( $localPath );
839 if ( $this->getConfig()->get( 'ResourceLoaderValidateStaticJS' ) ) {
840 // Static files don't really need to be checked as often; unlike
841 // on-wiki module they shouldn't change unexpectedly without
842 // admin interference.
843 $contents = $this->validateScriptFile( $fileName, $contents );
844 }
845 $js .= $contents . "\n";
846 }
847 return $js;
848 }
849
850 /**
851 * Gets the contents of a list of CSS files.
852 *
853 * @param array $styles List of media type/list of file paths pairs, to read, remap and
854 * concetenate
855 * @param bool $flip
856 * @param ResourceLoaderContext $context
857 *
858 * @throws MWException
859 * @return array List of concatenated and remapped CSS data from $styles,
860 * keyed by media type
861 *
862 * @since 1.27 Calling this method without a ResourceLoaderContext instance
863 * is deprecated.
864 */
865 public function readStyleFiles( array $styles, $flip, $context = null ) {
866 if ( $context === null ) {
867 wfDeprecated( __METHOD__ . ' without a ResourceLoader context', '1.27' );
868 $context = ResourceLoaderContext::newDummyContext();
869 }
870
871 if ( empty( $styles ) ) {
872 return array();
873 }
874 foreach ( $styles as $media => $files ) {
875 $uniqueFiles = array_unique( $files, SORT_REGULAR );
876 $styleFiles = array();
877 foreach ( $uniqueFiles as $file ) {
878 $styleFiles[] = $this->readStyleFile( $file, $flip, $context );
879 }
880 $styles[$media] = implode( "\n", $styleFiles );
881 }
882 return $styles;
883 }
884
885 /**
886 * Reads a style file.
887 *
888 * This method can be used as a callback for array_map()
889 *
890 * @param string $path File path of style file to read
891 * @param bool $flip
892 * @param ResourceLoaderContext $context
893 *
894 * @return string CSS data in script file
895 * @throws MWException If the file doesn't exist
896 */
897 protected function readStyleFile( $path, $flip, $context ) {
898 $localPath = $this->getLocalPath( $path );
899 $remotePath = $this->getRemotePath( $path );
900 if ( !file_exists( $localPath ) ) {
901 $msg = __METHOD__ . ": style file not found: \"$localPath\"";
902 wfDebugLog( 'resourceloader', $msg );
903 throw new MWException( $msg );
904 }
905
906 if ( $this->getStyleSheetLang( $localPath ) === 'less' ) {
907 $style = $this->compileLessFile( $localPath, $context );
908 $this->hasGeneratedStyles = true;
909 } else {
910 $style = file_get_contents( $localPath );
911 }
912
913 if ( $flip ) {
914 $style = CSSJanus::transform( $style, true, false );
915 }
916 $localDir = dirname( $localPath );
917 $remoteDir = dirname( $remotePath );
918 // Get and register local file references
919 $localFileRefs = CSSMin::getAllLocalFileReferences( $style, $localDir );
920 foreach ( $localFileRefs as $file ) {
921 if ( file_exists( $file ) ) {
922 $this->localFileRefs[] = $file;
923 } else {
924 $this->missingLocalFileRefs[] = $file;
925 }
926 }
927 return MemoizedCallable::call( 'CSSMin::remap',
928 array( $style, $localDir, $remoteDir, true ) );
929 }
930
931 /**
932 * Get whether CSS for this module should be flipped
933 * @param ResourceLoaderContext $context
934 * @return bool
935 */
936 public function getFlip( $context ) {
937 return $context->getDirection() === 'rtl';
938 }
939
940 /**
941 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
942 *
943 * @return array Array of strings
944 */
945 public function getTargets() {
946 return $this->targets;
947 }
948
949 /**
950 * Compile a LESS file into CSS.
951 *
952 * Keeps track of all used files and adds them to localFileRefs.
953 *
954 * @since 1.22
955 * @since 1.27 Added $context paramter.
956 * @throws Exception If less.php encounters a parse error
957 * @param string $fileName File path of LESS source
958 * @param ResourceLoaderContext $context Context in which to generate script
959 * @return string CSS source
960 */
961 protected function compileLessFile( $fileName, ResourceLoaderContext $context ) {
962 static $cache;
963
964 if ( !$cache ) {
965 $cache = ObjectCache::newAccelerator( CACHE_ANYTHING );
966 }
967
968 // Construct a cache key from the LESS file name and a hash digest
969 // of the LESS variables used for compilation.
970 $vars = $this->getLessVars( $context );
971 ksort( $vars );
972 $varsHash = hash( 'md4', serialize( $vars ) );
973 $cacheKey = wfGlobalCacheKey( 'LESS', $fileName, $varsHash );
974 $cachedCompile = $cache->get( $cacheKey );
975
976 // If we got a cached value, we have to validate it by getting a
977 // checksum of all the files that were loaded by the parser and
978 // ensuring it matches the cached entry's.
979 if ( isset( $cachedCompile['hash'] ) ) {
980 $contentHash = FileContentsHasher::getFileContentsHash( $cachedCompile['files'] );
981 if ( $contentHash === $cachedCompile['hash'] ) {
982 $this->localFileRefs = array_merge( $this->localFileRefs, $cachedCompile['files'] );
983 return $cachedCompile['css'];
984 }
985 }
986
987 $compiler = ResourceLoader::getLessCompiler( $this->getConfig(), $vars );
988 $css = $compiler->parseFile( $fileName )->getCss();
989 $files = $compiler->AllParsedFiles();
990 $this->localFileRefs = array_merge( $this->localFileRefs, $files );
991
992 $cache->set( $cacheKey, array(
993 'css' => $css,
994 'files' => $files,
995 'hash' => FileContentsHasher::getFileContentsHash( $files ),
996 ), 60 * 60 * 24 ); // 86400 seconds, or 24 hours.
997
998 return $css;
999 }
1000
1001 /**
1002 * Takes named templates by the module and returns an array mapping.
1003 * @return array of templates mapping template alias to content
1004 * @throws MWException
1005 */
1006 public function getTemplates() {
1007 $templates = array();
1008
1009 foreach ( $this->templates as $alias => $templatePath ) {
1010 // Alias is optional
1011 if ( is_int( $alias ) ) {
1012 $alias = $templatePath;
1013 }
1014 $localPath = $this->getLocalPath( $templatePath );
1015 if ( file_exists( $localPath ) ) {
1016 $content = file_get_contents( $localPath );
1017 $templates[$alias] = $content;
1018 } else {
1019 $msg = __METHOD__ . ": template file not found: \"$localPath\"";
1020 wfDebugLog( 'resourceloader', $msg );
1021 throw new MWException( $msg );
1022 }
1023 }
1024 return $templates;
1025 }
1026 }